package cn.ecasoft.common.message.controller;

import cn.ecasoft.common.message.mapper.NotifyInfoDAO;
import org.apache.ibatis.annotations.Mapper;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.ecasoft.common.message.utils.PushMessageUtil;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.StringUtils;



@Mapper
public class TaskUtils extends QuartzJobBean {
    @Autowired
    public NotifyInfoDAO notifyInfoDAO;
    @Autowired
    public PushMessageUtil pushMessageUtil;

    //查询所有未被发送的消息
    public void sendMSG() {
        List<HashMap> list = notifyInfoDAO.selecAll();
        if (list.size() > 0) {
            for (HashMap map : list) {
                if (StringUtils.isEmpty(map.get("MESSAGE"))) {
                    continue;
                }
                if(StringUtils.isEmpty(map.get("TOUSERID"))){
                    continue;
                }
                //2通过用户id 拿到对应的clientId
                //2.1通过用户Id 获取发送消息的客户端id
                String clientId = getClientId(map.get("TOUSERID").toString());
                //2.2获取发送的消息内容
                String message = map.get("MESSAGE").toString();
                //2.3获取发送的标题
                String title = StringUtils.isEmpty(map.get("TITLE")) ? "" : map.get("TITLE").toString();
                //3.发送消息
                try{
                    pushMessageUtil.sendGeTuiMessage(clientId, title, message);
                    //4.更新消息状态
                    notifyInfoDAO.updateStatus(map.get("TOUSERID").toString());
                }catch (Exception e){
                    e.printStackTrace();
                }
                //4.更新消息状态

                //
            }
        }
    }

    public String getClientId(String userid) {
        Map map = notifyInfoDAO.selectClientIdByUserId(userid);
        if(map!=null&&map.size()>0){
            return map.get("clientid").toString();
        }
        return "";
    }

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        sendMSG();
    }
}
